package com.qyhl.webtv.module_circle.circle.home;

import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.android.material.appbar.AppBarLayout;
import com.google.android.material.appbar.CollapsingToolbarLayout;
import com.google.android.material.tabs.TabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.qyhl.webtv.basiclib.base.BaseFragment;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.SingleChoiceDialog;
import com.qyhl.webtv.basiclib.utils.glide.GlideRoundTransform;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.circle.CircleHomeBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.DoubleClickBackToContentTopListener;
import com.qyhl.webtv.commonlib.utils.action.ActionConstant;
import com.qyhl.webtv.commonlib.utils.action.ActionLogUtils;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.inter.HomeActivityInterface;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.module_circle.R;
import com.qyhl.webtv.module_circle.R2;
import com.qyhl.webtv.module_circle.circle.friend.FriendMomentFragment;
import com.qyhl.webtv.module_circle.circle.moment.CircleMomentFragment;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.umeng.analytics.MobclickAgent;
import com.weavey.loading.lib.LoadingLayout;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by qyhl on 2018/1/17.
 * 圈子首页
 */

public class CircleHomeFragment extends BaseFragment implements CircleHomeContract.CircleView, DoubleClickBackToContentTopListener.IBackToContentTopView {
    @BindView(R2.id.title)
    TextView mTitle;
    @BindView(R2.id.add_topic)
    ImageView addTopic;
    @BindView(R2.id.topic_more)
    TextView topicMore;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.tabLayout)
    TabLayout tabLayout;
    @BindView(R2.id.topic_layout)
    LinearLayout topicLayout;
    @BindView(R2.id.collapsing_layout)
    CollapsingToolbarLayout collapsingLayout;
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.app_bar)
    AppBarLayout appBar;
    @BindView(R2.id.title_layout)
    RelativeLayout titleLayout;

    private View view;

    private CircleHomePresenter mPresenter;

    private CirclePagerAdapter circlePagerAdapter;

    private String title;

    private CommonAdapter commonAdapter;

    private List<CircleHomeBean.TagList> topicList;

    private List<String> stringList;

    // Frgaments
    private List<Fragment> mFragmentList;

    private EmptyWrapper emptyWrapper;

    private TextView textView;

//    private PopupMenu popupMenu;

    public void setTitle(String title) {
        this.title = title;
    }


    HomeActivityInterface homeActivityInterface;

    public void setHomeActivityInterface(HomeActivityInterface homeActivityInterface) {
        this.homeActivityInterface = homeActivityInterface;
    }

    public static CircleHomeFragment newInstance(String title, HomeActivityInterface homeActivityInterface) {
        CircleHomeFragment fragment = new CircleHomeFragment();
        fragment.setTitle(title);
        fragment.setHomeActivityInterface(homeActivityInterface);
        return fragment;
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (CommonUtils.getInstance().getSite() == 207) {
            return view = inflater.inflate(R.layout.circle_fragment_circle_home2, null);
        } else {
            return view = inflater.inflate(R.layout.circle_fragment_circle_home, null);
        }
    }

    @Override
    protected void create() {
        BusFactory.getBus().register(this);
        mPresenter = new CircleHomePresenter(this);
        initView();

    }

    @Override
    public void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true, 0.2f)
                .statusBarColor(R.color.white)
                .fitsSystemWindows(true)
                .init();

    }

    @Override
    protected void setListener() {
        setListeners();
    }

    @Override
    protected void onFirstVisible() {
        loadData();
    }

    @Override
    protected void onVisible() {

    }

    @Override
    protected void onHide() {

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

    }


    /**
     * 加载数据
     */
    private void loadData() {
        mPresenter.getTopic();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            ActionLogUtils.getInstance().onResume(this.getActivity(), ActionConstant.CIRCLEHOME);
        } else {
            ActionLogUtils.getInstance().onPause(this.getActivity(), ActionConstant.CIRCLEHOME);
        }
    }

    /**
     * 初始化界面
     */
    private void initView() {
        loadMask.setStatus(LoadingLayout.Loading);

        topicList = new ArrayList<>();

        mFragmentList = new ArrayList<>();
        //设置标题
        mTitle.setText(StringUtils.isEmpty(title) ? "圈子" : title);

        //设置布局管理器
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(linearLayoutManager);

        //初始化话题
        commonAdapter = new CommonAdapter<CircleHomeBean.TagList>(getContext(), R.layout.circle_item_circle_home_topic, topicList) {

            @Override
            protected void convert(ViewHolder holder, CircleHomeBean.TagList circleTopicBean, int position) {
                TextView title = holder.getView(R.id.title);
                ImageView cover = holder.getView(R.id.cover);

                title.setText("#" + circleTopicBean.getName() + "#");
                Glide.with(getActivity().getApplicationContext())
                        .load(circleTopicBean.getPic())
                        .apply(new RequestOptions().placeholder(R.drawable.cover_normal_default).error(R.drawable.cover_normal_default).optionalTransform(new GlideRoundTransform(4)))
                        .into(cover);
            }
        };

        emptyWrapper = new EmptyWrapper(commonAdapter);
        textView = new TextView(getContext());
        textView.setText("暂无话题,点击试试！");
        textView.setPadding(10, 40, 10, 40);
        textView.setBackgroundResource(R.color.global_background);
        textView.setTextColor(ContextCompat.getColor(getContext(), R.color.global_black_lv1));
        textView.setGravity(Gravity.CENTER);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        textView.setLayoutParams(param);

        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                textView.setText("加载中...");
                mPresenter.getTopic();
            }
        });
        emptyWrapper.setEmptyView(textView);
        recyclerView.setAdapter(emptyWrapper);
        //设置tab数据
        initTab();
        CircleMomentFragment circleMomentFragment = CircleMomentFragment.newInstance(this, homeActivityInterface);
        circleMomentFragment.setRefreshHotTopic(() -> doRefresh());
        mFragmentList.add(circleMomentFragment);
        mFragmentList.add(FriendMomentFragment.newInstance(homeActivityInterface));
        circlePagerAdapter = new CirclePagerAdapter(getChildFragmentManager(), mFragmentList);
        circlePagerAdapter.setData(stringList);

        viewPager.setAdapter(circlePagerAdapter);
        viewPager.setOffscreenPageLimit(3);
        tabLayout.setTabMode(TabLayout.MODE_FIXED);
        tabLayout.setupWithViewPager(viewPager);
    }


    private void toAddActivity(int position) {
        Bundle bundle = new Bundle();
        switch (position) {
            case 0:
                bundle.putInt("type", 1);
                break;
            case 1:
                bundle.putInt("type", 2);
                break;
            default:
                break;
        }

        CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
            @Override
            public void login(boolean isLogin) {
                if (isLogin) {
                    RouterManager.router(ARouterPathConstant.CIRCLE_ADD, bundle);
                } else {
                    RouterManager.routerLogin(getActivity(), 0);
                }
            }

            @Override
            public void error(String s) {
                RouterManager.routerLogin(getActivity(), 0);
            }
        });

        ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.CIRCLEADD);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //添加按钮监听
        addTopic.setOnClickListener(v -> {
//                //展示菜单
//                popupMenu.show();
            new SingleChoiceDialog.Builder(getContext()).setTitle("类型", R.color.global_gray_lv2)
                    .addList(new String[]{"图文", "视频"})
                    .setCancelTextColor(R.color.global_base)
                    .setOnItemClickListener((title, position) -> {
                        toAddActivity(position);
                    })
                    .show();
        });

        //话题监听
        commonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Bundle bundle = new Bundle();
                bundle.putString("id", topicList.get(position).getId() + "");
                RouterManager.router(ARouterPathConstant.CIRCLE_TOPIC, bundle);
                ActionLogUtils.getInstance().onEvent(ActionConstant.FLOWSCENE, ActionConstant.HOME, ActionConstant.CIRCLETOPIC);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });

        //更多话题监听
        topicMore.setOnClickListener(v -> {

        });

        //重载
        loadMask.setOnReloadListener(v -> {
            loadMask.setReloadButtonText("加载中...");
            mPresenter.getTopic();
        });

        titleLayout.setOnClickListener(new DoubleClickBackToContentTopListener(this));


    }


    /**
     * 刷新
     */
    public void doRefresh() {
        mPresenter.getTopic();
    }


    /**
     * 话题获取成功
     *
     * @param beanList
     */
    @Override
    public void topicSuccess(List<CircleHomeBean.TagList> beanList) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~~");
        if (textView != null) {
            textView.setText("暂无话题,点击试试！");
        }
        if (beanList.size() > 0) {
            appBar.setExpanded(true, true);
        }
        topicList.clear();
        topicList.addAll(beanList);
        emptyWrapper.notifyDataSetChanged();
    }

    /**
     * 话题获取出错
     *
     * @param msg
     */
    @Override
    public void topicError(String msg) {
        appBar.setVisibility(View.VISIBLE);
        loadMask.setStatus(LoadingLayout.Error);
        loadMask.setErrorText(msg);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无话题
     *
     * @param msg
     */
    @Override
    public void topicEmpty(String msg) {
        loadMask.setStatus(LoadingLayout.Success);
        appBar.setVisibility(View.GONE);
        loadMask.setReloadButtonText("点击重试~~");
    }

    /**
     * 无网络
     *
     * @param msg
     */
    @Override
    public void topicNetError(String msg) {
        appBar.setVisibility(View.VISIBLE);
        loadMask.setReloadButtonText("点击重试~~");
        loadMask.setNoNetworkText(msg);
        loadMask.setStatus(LoadingLayout.No_Network);
    }

    //初始化tab
    private void initTab() {
        stringList = new ArrayList<>();
        stringList.add("最新动态");
        stringList.add("好友动态");
    }

    @Override
    public void onResume() {
        super.onResume();
        //baidu
        //umeng
        MobclickAgent.onPageStart("圈子首页");
        MobclickAgent.onResume(getContext());
        GSYVideoManager.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        //baidu
        //umeng
        MobclickAgent.onPageEnd("圈子首页");
        MobclickAgent.onPause(getContext());
        GSYVideoManager.onPause();
    }

    public boolean onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(getActivity())) {
            return true;
        }
        return false;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            GSYVideoManager.releaseAllVideos();
        }
        super.onHiddenChanged(hidden);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        GSYVideoManager.releaseAllVideos();
        BusFactory.getBus().unregister(this);
    }


    /**
     * eventBus 接收器
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getMessage(Event.LoginMessage event) {
        if (event != null) {
            mPresenter.getTopic();
        }
    }

    /**
     * 评论事件
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void commentMessage(Event.CommentEvent event) {
        if (event != null) {
            appBar.setExpanded(false);
        }
    }

    /**
     * 双击顶部监听
     */
    @Override
    public void backToContentTop() {
        if (viewPager.getCurrentItem() == 0) {
            BusFactory.getBus().post(new Event.backToTopEvent(1));
        } else {
            BusFactory.getBus().post(new Event.backToTopEvent(2));
        }
    }


}
